//cart模块的小仓库
//引入接口文件
import { reqCartList, resDeleteCart, reqChangeChecked } from '@/api'
const state = {
    cartList: []
};
const actions = {
    //通过api里的接口函数调用，向服务器发请求，获取服务器的数据
    //获取购物车列表数据
    async cartList({ commit }) {
        let res = await reqCartList();
        if (res.code == 200) {
            commit('CARTLIST', res.data)
        }
    },
    //删除购物车某一个产品
    async deleteCart({ commit }, skuId) {
        let res = await resDeleteCart(skuId);
        if (res.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('delete failed'))
        }
    },
    //修改产品勾选状态
    async changeChecked({ commit }, { skuId, isChecked }) {
        let res = await reqChangeChecked(skuId, isChecked);
        if (res.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('change failed'))
        }
    },
    //删除勾选的商品
    deleteAllCart({ dispatch, getters }) {
        let promiseAll = [];
        getters.cartList.cartInfoList.forEach(element => {
            let promise = element.isChecked == 1 ? dispatch('deleteCart', element.skuId) : ''
            promiseAll.push(promise)
        });
        return Promise.all(promiseAll)
    },
    //全选或全不选产品
    changeCheckedAllOrNot({ dispatch, state }, isChecked) {
        let promiseAll = [];
        state.cartList[0].cartInfoList.forEach(element => {
            let promise = dispatch('changeChecked', { skuId: element.skuId, isChecked });
            promiseAll.push(promise)
        });
        return Promise.all(promiseAll)
    }
};
const mutations = {
    CARTLIST(state, cartList) {
        state.cartList = cartList
    }
};

const getters = {
    cartList() {
        return state.cartList[0] || []
    }
};

export default {
    state,
    mutations,
    actions,
    getters
}